package com.jdbc.guigu.student;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCTools {

	/**
	 * 使用 PreparedStatement执行 SQL 语句
	 * @param sql
	 * @param args: 填写 SQL 占位符的可变参数
	 */
	public static void update(String sql, Object ... args){  /*传入多个参数,高明！！！*/
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		
		try {
			connection = JDBCTools.getConnection();
			preparedStatement = connection.prepareStatement(sql);
			//本程序最强势的地方
			for(int i = 0; i < args.length; i++){
				/*参数index使用，从0来时。setObject()通用方法的index从1开始*/
				preparedStatement.setObject(i + 1, args[i]); 
			}
			preparedStatement.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			JDBCTools.releaseDB(null, preparedStatement, connection);
		}
	}
	/**
	 * 执行 SQL 的方法
	 * @param sql: insert, update 或 delete
	 */
	public static void update(String sql) {
		Connection connection = null;
		Statement statement = null;

		try {
			connection = getConnection();
			statement = connection.createStatement();
			statement.executeUpdate(sql);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			releaseDB(null, statement, connection);
		}
	}
	/**
	 * 获取数据库连接的方法
	 */
	public static Connection getConnection() throws Exception {

		Properties properties = new Properties();
		//注意使用这种方式读入时文件的位置，在src目录中
		InputStream inStream = JDBCTools.class.getClassLoader().getResourceAsStream("jdbc.properties");
		properties.load(inStream);
		
		String user = properties.getProperty("user");
		String password = properties.getProperty("password");
		String jdbcUrl = properties.getProperty("jdbcUrl");
		String driverClass = properties.getProperty("driverClass");
		
		Class.forName(driverClass);
		
		Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
		return connection;
	}

	/**
	 * 释放数据库资源的方法
	 * @param resultSet
	 * @param statement
	 * @param connection
	 */
	public static void releaseDB(ResultSet resultSet, Statement statement, Connection connection) {
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}


}
